package servlet;

import DBC.DatabaseConnection;
import Factory.DAOFactory;
import Spider.getCourse;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Connection;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: hank
 * @create: 2021-03-28 21:37
 **/
@WebServlet("/Login")
public class LoginServlet extends HttpServlet {
    private final DatabaseConnection dbc = new DatabaseConnection();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.doGet(request, response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
        response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        response.setHeader("Content-Type","text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String user = request.getParameter("user");
        String password = request.getParameter("password");
        Map<String, Object> map = new HashMap<>();
        try {
            if (DAOFactory.UserPwdInstance(this.dbc.getConn()).getPassword(user).isEmpty()){
                try {
                    if (getCourse.forCourse(user, password, this.dbc.getConn())) {
                        System.out.println("已获取"+user+"课表");
                        map.put("StateCode", 200);
                        DAOFactory.UserPwdInstance(this.dbc.getConn()).saveUserPwd(user, password);
                        System.out.println("已保存"+user+"数据");
                    }
                }catch (NullPointerException e){
                    map.put("StateCode", 500);
                } catch (SQLException e) {
                    e.printStackTrace();
                    map.put("StateCode", 200);
                }
            }else if (password.equals(DAOFactory.UserPwdInstance(this.dbc.getConn()).getPassword(user).get(0).getPassword())){
                map.put("StateCode", 200);
            }else{
                map.put("StateCode", 500);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            map.put("userID", user);
            response.getWriter().print(com.alibaba.fastjson.JSONObject.toJSONString(map));
        }
        System.out.println(user+"Login in "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }
}
